package com.chris.cc.user.mapper;

import org.apache.commons.lang.StringUtils;

import java.util.Map;

/**
 * Copyright (c) 2018-2025, chris All rights reserved.
 * <p>
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * <p>
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * <p>
 * Author: haoka (haokang207@126.com)
 * <p>
 * Date: 2018/9/28 14:04
 * 复杂查询编辑器
 **/
public class ComplexSelectProvider {

    /**
     * 查询角色列表（当前用户拥有授予权限的）
     *
     * @param params
     * @return
     */
    public String roleSelect4User(Map<String, Object> params) {
        Long userId = (Long) params.get("userId");
        Boolean enable = (Boolean) params.get("enable");
        String keyword = (String) params.get("keyword");
        long offset = (long) params.get("offset");
        int pageSize = (int) params.get("pageSize");
        String roleCondition = enable != null ? "AND enable=" + (enable ? 1 : 0) : "";
        String keywordCondition = StringUtils.isNotBlank(keyword) ?
                " AND (name like '%" + keyword + "%' OR code like '%" + keyword + "%' OR description like '%" + keyword + "%')" : "";
        return "SELECT r.* FROM u_role r " +
                "LEFT JOIN u_user_role ur ON ur.role_Id=r.role_id AND ur.user_id=" + userId +
                " WHERE 1=1 " +
                roleCondition +
                keywordCondition +
                " LIMIT " + offset + "," + pageSize;
    }

    /**
     * 查询角色列表总数（当前用户拥有授予权限的）
     *
     * @param params
     * @return
     */
    public String roleSelectCount4User(Map<String, Object> params) {
        Long userId = (Long) params.get("userId");
        Boolean enable = (Boolean) params.get("enable");
        String keyword = (String) params.get("keyword");
        String roleCondition = enable != null ? "AND enable=" + (enable ? 1 : 0) : "";
        String keywordCondition = StringUtils.isNotBlank(keyword) ?
                " AND (name like '%" + keyword + "%' OR code like '%" + keyword + "%' OR description like '%" + keyword + "%')" : "";
        return "SELECT count(1) FROM u_role r " +
                "LEFT JOIN u_user_role ur ON ur.role_Id=r.role_id AND ur.user_id=" + userId +
                " WHERE 1=1 " +
                roleCondition +
                keywordCondition;
    }
}
